# import imp
import sys
import os
from time import sleep
from fastapi import APIRouter,Request
from sse_starlette.sse import EventSourceResponse
# from fastapi import WebSocket, WebSocketDisconnect
# from pydantic import Json, ValidationError
from revChatGPT.V3 import Chatbot

# from message_forward.manger import user_manager, max_users
# from message_forward.models import Message
from pydantic import BaseModel # 引入BaseModel

userServerS= APIRouter()

jsonMap = {}

index = 0

def get_user_id():
    global index
    index += 1
    return f'user{index}'

# async def receive_query_data(user_id):
#     try:
#         data = await user_manager[user_id].receive_json()
#         if data is not None and data != {} and 'msg' in data:
#             # return Message(**data)
#             return data
#     except ValidationError:
#         await user_manager[user_id].send_json(
#             {'msg': 'Data format error or query parameter too '
#                     'long. The query parameter is limited to '
#                     '300 characters or less.', 'id': user_id})
#     except WebSocketDisconnect:
#         raise WebSocketDisconnect

class Item(BaseModel):
    jsonDto:dict
chatbot =  Chatbot(api_key="")

@userServerS.get("/sse/data")
def sse(request: Request):
    print(request.query_params.get('id'))
    event_generator = status_event_generator(request)
    return EventSourceResponse(event_generator)

status_stream_delay = 1  # second
status_stream_retry_timeout = 30000  # milisecond

# 其实就是绑定函数事件 一直在跑循环
async def status_event_generator(request):
    try:
        user_id = request.query_params.get('id')
        if not await request.is_disconnected()==True and jsonMap != {} and jsonMap is not None:
            for data in chatbot.ask(jsonMap[user_id],'user',user_id):
                print(data)
                # response = data["message"]
                # print(data, end="", flush=True)
                sleep(0.04)# 可以去掉，加这个只是为了页面逐字打印效果更明显。
                jsonDto = {'msg': data,'id': user_id}
                yield {
                    "event": "message",
                    "retry": status_stream_retry_timeout,
                    "data": str(jsonDto)+ "\n\n"
                }
            yield {
                "event": "close",
                "retry": status_stream_retry_timeout
            }
    except ConnectionResetError:
        print('********[WinError 10054] 远程主机强迫关闭了一个现有的连接。******')
        yield {
            "event": "close",
            "retry": status_stream_retry_timeout
        }
    except Exception as e:
        except_type, except_value, except_traceback = sys.exc_info()
        except_file = os.path.split(except_traceback.tb_frame.f_code.co_filename)[1]
        exc_dict = {
            "报错类型": except_type,
            "报错信息": except_value,
            "报错文件": except_file,
            "报错行数": except_traceback.tb_lineno,
        }
        print(exc_dict)
        yield {
            "event": "close",
            "retry": status_stream_retry_timeout
        }
        
    # times=0
    # while True:
    #     if not await request.is_disconnected()==True:
    #         yield {
    #             "event": "message",
    #             "retry": status_stream_retry_timeout,
    #             "data": "data:" + "times"+str(times)+ "\n\n"
    #         }
    #     print("alive")
    #     times+=1
    #     await asyncio.sleep(status_stream_delay)

@userServerS.post("")
def echo(jsonDto: dict):
    print(jsonDto)
    if jsonDto['id'] is None:
        user_id = get_user_id()
        jsonDto['id'] = user_id
    else:
        user_id = jsonDto['id']
    jsonMap[user_id] = jsonDto['msg']
    return jsonDto
    

# @userServer.websocket("")
# async def websocket_endpoint(ws: WebSocket):
#     await ws.accept()
#     # if not len(user_manager) < max_users:
#     #     await ws.send_json({'msg': 'User overload, please try again later.'})
#     #     await ws.close()
#     # else:
#     user_id = get_user_id()
#     user_manager[user_id] = ws
#     wait_status = False
#     # await ws.send_json({'msg': f'Connection successful, your ID is {user_id}.'})
#     await ws.send_json({'msg': f'连接成功','id': user_id})

#     try:
#         while True:
#             user_id_t = user_id
#             dataR = await receive_query_data(user_id_t)
#             if dataR:
#                 if wait_status:
#                     await ws.send_json({'msg': 'Please wait for the previous message to return.'})
#                 else:
#                     chatbot = Chatbot(config={
#                         "email": "ranijinoe+gsnql@gmail.com",
#                         "password": "48bcf8a1"
#                     })
#                     if dataR != {} and dataR is not None and 'id' in dataR:
#                         print(dataR)
#                         user_id_t = dataR['id']

#                     if  user_id_t in user_conversation_ids and user_conversation_ids[user_id_t] is not None and user_conversation_ids[user_id_t] != '':
#                         conversation_id = user_conversation_ids[user_id_t]
#                         print('已有的conversation_id：' + conversation_id)
#                     else:
#                         # str(uuid.uuid4())
#                         conversation_id = None
#                         user_conversation_ids[user_id_t] = conversation_id

#                     response = ""
#                     try:
#                         for data in chatbot.ask(dataR['msg'], conversation_id, None, 360):
#                             response = data["message"]
#                         if conversation_id is None and data is not None:
#                             conversations = chatbot.get_conversations(0, 20, None)
#                             conversation_id = conversations[0]['id']
#                             print('初次获取到的conversation_id：' + conversation_id)
#                             user_conversation_ids[user_id_t] = conversation_id
#                         dataNew = {'msg': response,'id': user_id_t}
#                         print(response)
#                         await user_manager[user_id_t].send_json(dataNew)
#                     except ConnectionResetError:
#                         print('********[WinError 10054] 远程主机强迫关闭了一个现有的连接。******')
#                         if user_id in user_manager:
#                             await user_manager[user_id_t].close()
#                             user_manager.pop(user_id_t)
#                     except Exception as e:
#                         if user_id in user_manager:
#                             await user_manager[user_id_t].close()
#                             user_manager.pop(user_id_t)
#                         except_type, except_value, except_traceback = sys.exc_info()
#                         except_file = os.path.split(except_traceback.tb_frame.f_code.co_filename)[1]
#                         exc_dict = {
#                             "报错类型": except_type,
#                             "报错信息": except_value,
#                             "报错文件": except_file,
#                             "报错行数": except_traceback.tb_lineno,
#                         }
#                         print(exc_dict)

                    

#     except WebSocketDisconnect:

#         print(f'{user_id} user disconnected')
#         user_manager[user_id].close()
#         user_manager.pop(user_id)
